﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using com.hyrentals.common;
using com.hyrentals.webcommon.api;


namespace com.hyrentals.webcommon.filter
{
    public class OnErrorAttribute : HandleErrorAttribute
    {
        public readonly ComponentType ComponentType;
        public OnErrorAttribute(ComponentType componentType)
        {
            ComponentType = componentType;
        }

        public override void OnException(ExceptionContext filterContext)
        {
            bool debugEnable = false;
            try
            {
                debugEnable = bool.Parse(filterContext.RequestContext.HttpContext.Request["debug"].ToString());
            }
            catch
            {
                debugEnable = false;
            }

            if (debugEnable)
            {
                base.OnException(filterContext);
                return;
            }

            if (filterContext.ExceptionHandled)
            {
                return;
            }

            Logger.Error(string.Format("component: {0}. url: {1}",
                  ComponentType.ToString(),
                  filterContext.HttpContext.Request.Url.AbsoluteUri),
                  filterContext.Exception);

            if (filterContext.Exception is HttpException || filterContext.Exception is UnauthorizedAccessException)
            {
                base.OnException(filterContext);
                return;
            }

            // Prepare the response code.
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            filterContext.Result = new RedirectResult("/error/internalerror");
            return;
        }
    }
}
